"""
情感分析API路由
提供情感分析相关的API接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field
from datetime import datetime
from sqlalchemy.orm import Session

from core.database import get_db
from core.auth import get_current_active_user
from models.user import User
from services.analysis.sentiment_analyzer import SentimentAnalyzer, SentimentAnalysisFilters
from services.analysis.base_analyzer import get_analysis_service

# 创建路由器
sentiment_analysis_router = APIRouter()

# 请求模型
class SentimentAnalysisRequest(BaseModel):
    """情感分析请求模型"""
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")
    sentiment_type: Optional[str] = Field(None, description="情感类型: positive, negative, neutral")
    min_confidence: Optional[float] = Field(None, ge=0.0, le=1.0, description="最小置信度")
    keyword_filter: Optional[str] = Field(None, description="关键词过滤")
    limit: Optional[int] = Field(1000, ge=1, le=10000, description="返回记录限制")
    offset: Optional[int] = Field(0, ge=0, description="偏移量")

class SentimentTrendsRequest(BaseModel):
    """情感趋势请求模型"""
    sentiment_type: Optional[str] = Field(None, description="特定情感类型")
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")
    granularity: Optional[str] = Field("day", description="时间粒度: day, week, month")

class KeywordAnalysisRequest(BaseModel):
    """关键词分析请求模型"""
    keyword: str = Field(..., description="分析的关键词")
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")


@sentiment_analysis_router.post("/analyze")
async def analyze_sentiment(
    request: SentimentAnalysisRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    执行情感分析

    返回完整的情感分析结果，包括：
    - 基础统计信息
    - 情感分布数据
    - 情感趋势分析
    - 关键词分析
    - 置信度分析
    - 时间序列数据
    - 热门情感内容
    """
    try:
        # 创建过滤器
        filters = SentimentAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date
        filters.sentiment_type = request.sentiment_type
        filters.min_confidence = request.min_confidence
        filters.keyword_filter = request.keyword_filter
        filters.limit = request.limit
        filters.offset = request.offset

        # 执行分析
        analyzer = SentimentAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        return {
            "code": 200,
            "message": "情感分析完成",
            "data": result.data,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"情感分析失败: {str(e)}")


@sentiment_analysis_router.get("/distribution")
async def get_sentiment_distribution(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    sentiment_type: Optional[str] = Query(None, description="特定情感类型"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取情感分布统计数据"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.sentiment_type = sentiment_type

        analyzer = SentimentAnalyzer(db)
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_sentiment_distribution(query, filters)

        return {
            "code": 200,
            "message": "获取情感分布成功",
            "data": distribution,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取情感分布失败: {str(e)}")


@sentiment_analysis_router.get("/trends")
async def get_sentiment_trends(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    sentiment_type: Optional[str] = Query(None, description="特定情感类型"),
    granularity: Optional[str] = Query("day", description="时间粒度: day, week, month"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取情感趋势分析"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.sentiment_type = sentiment_type

        analyzer = SentimentAnalyzer(db)
        query = analyzer.build_base_query(filters)
        trends = analyzer.get_sentiment_trends(query, filters)

        return {
            "code": 200,
            "message": "获取情感趋势成功",
            "data": trends,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取情感趋势失败: {str(e)}")


@sentiment_analysis_router.get("/keywords")
async def get_keyword_analysis(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    sentiment_type: Optional[str] = Query(None, description="特定情感类型"),
    limit: Optional[int] = Query(20, ge=1, le=100, description="返回关键词数量限制"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取关键词分析"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.sentiment_type = sentiment_type

        analyzer = SentimentAnalyzer(db)
        query = analyzer.build_base_query(filters)
        keyword_analysis = analyzer.get_keyword_analysis(query, filters)

        return {
            "code": 200,
            "message": "获取关键词分析成功",
            "data": keyword_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取关键词分析失败: {str(e)}")


@sentiment_analysis_router.get("/confidence-analysis")
async def get_sentiment_confidence_analysis(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    sentiment_type: Optional[str] = Query(None, description="特定情感类型"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取情感置信度分析"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.sentiment_type = sentiment_type

        analyzer = SentimentAnalyzer(db)
        query = analyzer.build_base_query(filters)
        confidence_analysis = analyzer.get_confidence_analysis(query, filters)

        return {
            "code": 200,
            "message": "获取置信度分析成功",
            "data": confidence_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取置信度分析失败: {str(e)}")


@sentiment_analysis_router.get("/popular-sentiments")
async def get_popular_sentiments(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    sentiment_type: Optional[str] = Query(None, description="特定情感类型"),
    limit: Optional[int] = Query(10, ge=1, le=50, description="返回记录数量限制"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取热门情感内容"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.sentiment_type = sentiment_type

        analyzer = SentimentAnalyzer(db)
        query = analyzer.build_base_query(filters)
        popular_sentiments = analyzer.get_popular_sentiments(query, filters, limit)

        return {
            "code": 200,
            "message": "获取热门情感内容成功",
            "data": popular_sentiments,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取热门情感内容失败: {str(e)}")


@sentiment_analysis_router.post("/keyword-analysis")
async def analyze_specific_keyword(
    request: KeywordAnalysisRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """分析特定关键词"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date
        filters.keyword_filter = request.keyword

        analyzer = SentimentAnalyzer(db)
        query = analyzer.build_base_query(filters)
        keyword_analysis = analyzer.get_keyword_analysis(query, filters)

        return {
            "code": 200,
            "message": "关键词分析完成",
            "data": keyword_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"关键词分析失败: {str(e)}")


@sentiment_analysis_router.get("/time-series")
async def get_sentiment_time_series(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    sentiment_type: Optional[str] = Query(None, description="特定情感类型"),
    granularity: Optional[str] = Query("day", description="时间粒度: day, week, month"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取情感时间序列数据"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.sentiment_type = sentiment_type

        analyzer = SentimentAnalyzer(db)
        time_series = analyzer.get_time_series_data(filters, granularity)

        return {
            "code": 200,
            "message": "获取时间序列成功",
            "data": time_series,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取时间序列失败: {str(e)}")


@sentiment_analysis_router.get("/sentiment-summary")
async def get_sentiment_summary(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取情感分析摘要"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date

        analyzer = SentimentAnalyzer(db)
        basic_stats = analyzer.get_basic_statistics(filters)

        # 获取简要的情感分布
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_sentiment_distribution(query, filters)

        # 获取置信度分析
        confidence_analysis = analyzer.get_confidence_analysis(query, filters)

        summary = {
            "basic_statistics": basic_stats,
            "sentiment_overview": {
                "dominant_sentiment": distribution.get("dominant_sentiment", "无"),
                "dominant_percentage": distribution.get("dominant_percentage", 0),
                "total_sentiments": distribution.get("total_types", 0)
            },
            "sentiment_breakdown": {
                "types": distribution.get("types", [])[:3],
                "counts": distribution.get("counts", [])[:3],
                "percentages": distribution.get("percentages", [])[:3]
            },
            "average_confidence": confidence_analysis.get("average_confidence", 0)
        }

        return {
            "code": 200,
            "message": "获取情感摘要成功",
            "data": summary,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取情感摘要失败: {str(e)}")


@sentiment_analysis_router.get("/export")
async def export_sentiment_data(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    sentiment_type: Optional[str] = Query(None, description="特定情感类型"),
    format: str = Query("json", description="导出格式: json, csv"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """导出情感分析数据"""
    try:
        filters = SentimentAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.sentiment_type = sentiment_type

        analyzer = SentimentAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        if format == "json":
            return {
                "code": 200,
                "message": "数据导出成功",
                "data": result.data,
                "format": "json",
                "timestamp": datetime.now().isoformat()
            }
        elif format == "csv":
            # 这里可以实现CSV导出逻辑
            raise HTTPException(status_code=400, detail="CSV导出功能待实现")
        else:
            raise HTTPException(status_code=400, detail="不支持的导出格式")

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导出数据失败: {str(e)}")